from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status

def custom_exception_handler(exc, context):
    """
    自定义异常处理
    
    Args:
        exc: 异常
        context: 上下文
        
    Returns:
        Response: 处理后的响应
    """
    # 首先调用REST framework默认的异常处理
    response = exception_handler(exc, context)
    
    # 如果默认处理程序返回为None，则将其转换为JSON格式响应
    if response is None:
        return Response(
            {
                'success': False,
                'message': str(exc),
                'data': None
            },
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )
    
    # 为已处理的异常添加额外的格式
    if not getattr(response, 'data', None):
        response.data = {}
    
    response.data['success'] = False
    
    # 确保有message字段
    if not response.data.get('message'):
        response.data['message'] = str(exc)
    
    # 确保有data字段
    if 'data' not in response.data:
        response.data['data'] = None
    
    return response 